package com.zdp.nio.channel.socketchannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * SocketChannel 方法使用示例
 */
public class SocketChannelTest {

    private static boolean run = true;

    public static void main(String[] args) throws IOException {
        String ip = "110.41.5.4";
        int port = 8081;
        printSocketChannel(ip,port);

    }

    /**
     * 监听 ip:port ，将该端口传输过来的数据输出
     * @param ip
     * @param port
     */
    public static void printSocketChannel(String ip,int port) throws IOException {
        // 1. 获取 SocketChannel对象
        SocketChannel channel = SocketChannel.open();
        // 2. 设置非阻塞模式
        channel.configureBlocking(false);
        // 3. 发起连接
        channel.connect(new InetSocketAddress(ip,port));

        // other. 初始化 Buffer,用于读取/写入通道数据
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while(run){
            while(!channel.finishConnect()){
            }
            // 4. 读取流
            int readLength = 0;
            // socket:若流没有数据，则读取的长度为0( 没有一个终止的标志，不同于 FileChannel)
            while((readLength = channel.read(buffer)) != 0){
                // 4.1 打印数据
                buffer.flip();
                byte[] bytes = new byte[readLength];
                buffer.get(bytes);
                System.out.println("> 数据打印: " + new String(bytes,"utf-8"));
                buffer.clear();
            }
        }
        // 5. 发送结束标志
        channel.shutdownOutput();

    }

    public static void stopPrintSocketChannel(){
        run = true;
    }


}
